package br.ita.comp.ces22.quiz.core.dao.jpa;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import br.ita.comp.ces22.quiz.core.dao.UserDAO;
import br.ita.comp.ces22.quiz.domain.Rank;
import br.ita.comp.ces22.quiz.domain.User;

public class UserJPADAO extends UserDAO{

	private EntityManager em;
	
	public UserJPADAO(){
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("mysql");
		em = emf.createEntityManager();
	}
	
	public User getById(Object oLogin){
		String login = (String) oLogin;
		User user = 
		(User) em.createNamedQuery("User.findById").setParameter("login",login).getSingleResult();
		return user;
	}
	public void insert(User user){
		em.getTransaction().begin();
		em.persist(user);
		em.getTransaction().commit();
	}
	public void update(User user){
		em.getTransaction().begin();
		em.merge(user);
		em.getTransaction().commit();
		
	}
	public List<Rank> getTopList(int qtde){
		List<Rank> todos = 
		em.createNamedQuery("User.findAll").getResultList();
		
		ArrayList<Rank> lRank = new ArrayList<Rank>();
		

		for(int i=0;i<todos.size();i++){
			boolean ok=false;
			Integer aux = 0;
			aux = todos.get(i).getHit();
			for(int j=0;j<lRank.size();j++){
				if(aux>lRank.get(j).getHit()){
					lRank.add(j,todos.get(i));
					ok=true;
					break;
				}
				else if(j>=qtde){
					ok=true;
					break;
				}
			}
			if(!ok){
				lRank.add(todos.get(i));
			}
		}
		
		for(int i=qtde;i<lRank.size();i++){
			lRank.remove(i);
		}
		
		return lRank;
	}

	public List<User> getObservers() {
		List<User> lista = em.createNamedQuery("User.findAll").getResultList();
		for(int i=0;i<lista.size();i++){
			if(lista.get(i).getObserver() == 0) lista.remove(i);
		}
		return lista;
	}
	public List<User> getNonObservers() {
		List<User> lista = em.createNamedQuery("User.findAll").getResultList();
		for(int i=0;i<lista.size();i++){
			if(lista.get(i).getObserver() == 1) lista.remove(i);
		}
		return lista;
	}
}
